import Vue from 'vue'
import VueRouter from 'vue-router'
import Register from '../views/register.vue'
import Login from '../views/login.vue'
import Index from '../views/index.vue'
import Notfound from '../views/404.vue'
import Article from '../views/article.vue'
import Star from '../views/star.vue'
import Like from '../views/like.vue'
import Articledetaile from '../views/article-detail.vue'
import Manager from '../views/manager.vue'

import { getToken } from '../utils/token'


Vue.use(VueRouter)

const routes = [
  {
    //路径
    path: "/register",
    //页面组件
    component: Register
  },
  {
    //路径
    path: "/login",
    //页面组件
    component: Login
  },
  {
    //路径
    path: "/",
    //页面组件
    component: Index,
    //重定向，进入首页，默认访问面经列表
    // 重定向要写完整路径，完整路径是父页面路径 + 子页面路径
    redirect: '/article',
    //嵌套路由配置，给首页配置子页面
    children: [
      {
        //路径
        // 子页面路径 ，不写/开头
        //  Vue会帮你把父页面路径拼接过来
        path: 'article',
        component: Article
      },
      {

        path: 'star',
        component: Star
      },
      {

        path: 'like',
        component: Like
      },
      {

        path: 'manager',
        component: Manager
      }
    ]
  },
  {
    path: '/article-detail/:id',
    component: Articledetaile
  },

  //404页面放在最下面
  {
    path: '*',
    component: Notfound
  }

]

const router = new VueRouter({
  routes
})

//注册导航守卫
router.beforeEach((to, from, next) => {
  //判断即将进入的是不是登录跟注册页面   是的话  直接进入
  if (to.path === '/login' || to.path === '/register') {
    next()
  } else {
    //看本地存储是否有token 有就进入 没有就跳转到登录页面
    if (getToken()) {
      next()
    }
    else {
      next('/login')
    }
  }
})
export default router
